import 'package:flutter/material.dart';
import 'package:flutterDemo/database/sqlite_helper.dart';

class KnowledgePage extends StatefulWidget {
  const KnowledgePage({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _KnowledgePageState createState() => _KnowledgePageState();
}

class _KnowledgePageState extends State<KnowledgePage> {
  final SQLiteHelper dbHelper = SQLiteHelper();
  List<Map<String, dynamic>> _knowledgeItems = [];

  // 用于编辑的文本控制器
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _initDatabase();
    _refreshData();
  }

  Future<void> _initDatabase() async {
    await dbHelper.database;
  }

  Future<void> _refreshData() async {
    final data = await dbHelper.queryAll();
    setState(() {
      _knowledgeItems = data;
    });
  }

  // 添加数据弹窗
  Future<void> _showAddDialog() async {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('添加新知识'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _titleController,
                decoration: const InputDecoration(hintText: '输入标题'),
              ),
              TextField(
                controller: _contentController,
                decoration: const InputDecoration(hintText: '输入内容'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                _titleController.clear();
                _contentController.clear();
              },
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                await dbHelper.insert({
                  'title': _titleController.text,
                  'content': _contentController.text,
                  'createdAt': DateTime.now().toString(),
                });
                _refreshData();
                Navigator.pop(context);
                _titleController.clear();
                _contentController.clear();
              },
              child: const Text('添加'),
            ),
          ],
        );
      },
    );
  }

  // 编辑数据弹窗
  Future<void> _showEditDialog(Map<String, dynamic> item) async {
    _titleController.text = item['title'];
    _contentController.text = item['content'];

    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('编辑知识条目'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _titleController,
                decoration: const InputDecoration(hintText: '输入标题'),
              ),
              TextField(
                controller: _contentController,
                decoration: const InputDecoration(hintText: '输入内容'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                await dbHelper.update({
                  'id': item['id'],
                  'title': _titleController.text,
                  'content': _contentController.text,
                  'createdAt': DateTime.now().toString(),
                });
                _refreshData();
                Navigator.pop(context);
                _titleController.clear();
                _contentController.clear();
              },
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }

  // 删除确认弹窗
  Future<void> _showDeleteDialog(int id) async {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: const Text('确定要删除这条记录吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                await dbHelper.delete(id);
                _refreshData();
                Navigator.pop(context);
              },
              child: const Text('删除'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(title: Text('知识库管理')),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddDialog,
        child: const Icon(Icons.add),
      ),
      body: ListView.builder(
        itemCount: _knowledgeItems.length,
        itemBuilder: (context, index) {
          final item = _knowledgeItems[index];
          return Card(
            color: Colors.purple[50],
            child: ListTile(
              leading: CircleAvatar(
                radius: 15,
                child: Text('${index + 1}'), // 显示序号
                backgroundColor: Colors.purple,
                foregroundColor: Colors.white,
              ),
              title: Text(item['title']),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item['content']),
                  const SizedBox(height: 5),
                  Text(
                    '创建时间：${item['createdAt']}',
                    style: const TextStyle(color: Colors.grey, fontSize: 12),
                  ),
                ],
              ),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                    icon: const Icon(Icons.edit, color: Colors.blue),
                    onPressed: () => _showEditDialog(item),
                  ),
                  IconButton(
                    icon: const Icon(Icons.delete, color: Colors.red),
                    onPressed: () => _showDeleteDialog(item['id']),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    super.dispose();
  }
}
